
import json
import os
import subprocess
from pathlib import Path
from contextlib import contextmanager

def load_repos(json_file):
    try:
        with open(json_file) as f:
            data = json.load(f)
            return data.get("dependency", [])
    except Exception as e:
        print(f"加载配置文件错误: {e}")
        return []

@contextmanager
def temp_chdir(path):
    old_dir = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(old_dir)

def run_bash_popen(script_path):
    process = subprocess.Popen(
        ["bash", script_path],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True,
    )
    stdout, stderr = process.communicate()
    if process.returncode != 0 :
        print("ERROR:({})".format(process.returncode))
        print(stderr)
        return False

    print(stdout)
    return True

def git_clone(cmd):
    print(cmd)
    try:
        result = subprocess.run(
            cmd,
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        print(result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print("ERROR:")
        print(e.stderr)
        return False, f"Error: {e.stderr}"
    except Exception as e:
        return False, f"System error: {str(e)}"

def clone_repo(repo_info):
    print("clone ...")
    repo_dir = Path("code/{}".format(repo_info["name"]))
    if repo_dir.exists():
        print(f"仓库 {repo_info['name']} 已存在，跳过克隆")
        return True
    
    ret = False
    cmd = ["git", "clone", "-b", repo_info["branch"], repo_info["url"], repo_info["name"]]
    with temp_chdir("code"):
        ret = git_clone(cmd)
    return ret

def run_build_script(repo_name):
    build_script = Path("code/{}/build_ohos.sh".format(repo_name))
    if not build_script.exists():
        print(f"{repo_name} 中未找到 build.sh 脚本")
        return False

    ret = False
    with temp_chdir("code/{}".format(repo_name)):
        cmd = "./build_ohos.sh"
        ret = run_bash_popen(cmd)
    
    return ret    

def main(json_file="dependency.json"):
    try:
        repos = load_repos(json_file)
        if not isinstance(repos, list):
            repos = [repos]  # 处理单个仓库的情况
            
        for repo in repos:
            if clone_repo(repo):
                run_build_script(repo["name"])
    except FileNotFoundError:
        print(f"错误: 未找到 {json_file} 文件")
    except json.JSONDecodeError:
        print(f"错误: {json_file} 不是有效的JSON文件")

if __name__ == "__main__":
    main()

